<?php

#null - Empty: yes
#0 - Empty: no
#string "0" - Empty: no
#false - Empty: yes
#false ($allow_false = true) - Empty: yes
#true - Empty: no
#string "foo" - Empty: no
#white space "     " - Empty: no
#white space ($allow_ws = true) "     " - Empty: no
#empty array - Empty: yes

function empty_string($var) {
    if ($var === '0' || $var === 0)
        return false;
    return empty($var);
}

/*
 * get value from hash, with default value and data type check support
 */

function get_hash_param($hash, $param, $default = null, $data_type = null) {
    $value = $default;
    if (isset($hash[$param])) {
        $value = $hash[$param];
    }

    #$data_type=''
    if ($data_type != null) {
        return sanitizeOne($value, $data_type, $default);
    }
    return $value;
}

/* description:
 *   filename:
 *   filecontent:
 *   filemode:  in octet please
 */

function WriteFile($filename, $filecontent, $filemode = null) {
    error_log("Writing to file:" . $filename);
    $fh = fopen($filename, 'w') or die("CommonUtil::WriteFile: can't open file"); // ??? fixme
    //??? fixme no filelock needed?
    fwrite($fh, $filecontent);
    fclose($fh);
    if (!is_null($filemode)) {
        //example: chmod("/somedir/somefile", 0755);  // octal; correct value of mode
        chmod($filename, $filemode);
    }
}

// Description:
//   append content to end of file
function AppendFile($filename, $filecontent) {

    if (file_exists($filename)) {
        $fh = fopen($filename, 'a') or die("CommonUtil::AppendFile: can't open file"); // ??? fixme
        fwrite($fh, $filecontent);
        fclose($fh);
    } else {
        WriteFile($filename, $filecontent);
    }
}

/* * ****************** Start input data processing ******************* */

/**
 * Sanitize (means some cleanup) only one variable .
 * Returns the variable sanitized according to the desired type or true/false
 * for certain data types if the variable does not correspond to the given data type.
 *
 * NOTE: True/False is returned only for telephone, pin, id_card data types
 *
 * @param $var: mixed The variable itself
 * @param $check_rule: string A string containing the desired variable type
 * @param $check_rule:  -or- array('type'=>value_hint)
 * @return FALSE: if the value is not valid under that criteria
 *         The sanitized variable or true/false
 */
#http://www.php.net/manual/en/filter.filters.validate.php
#http://www.php.net/manual/en/filter.filters.sanitize.php
#http://www.php.net/manual/en/ref.filter.php
#http://php.net/manual/en/function.strip-tags.php
function sanitizeOne($value, $check_rule, $optional_default_value = '') {

    $h_check_rule = array(); # hash;

    if (is_array($check_rule)) { # hash actually
        $h_check_rule = $check_rule;
    } else {
        $a_temp = explode(',', $check_rule);
        foreach ($a_temp as $temp) {
            $h_check_rule[$temp] = 1; # convert the string as array, for mulitple value verification
        }
    }

    $error = 0; # assume no error
    foreach ($h_check_rule as $rule => $check_hint) {
        switch ($rule) {
            case 'empty':
                $error = empty($value) === true ? 1 : 0;
                break;
            case 'int':
                //$error = filter_var($value, FILTER_VALIDATE_INT) === false || $value<0 ? 1 : 0;
                $error = !is_numeric($value) || $value < 0 ? 1 : 0;
                break;
            case 's:int':
                $value = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
                $error = !is_numeric($value) || $value < 0 ? 1 : 0;
                //$error = filter_var($value, FILTER_VALIDATE_INT) === false || $value<0 ? 1 : 0 ;
                break;

            case 'e:int': //允許空值與數字
                if (!empty($value) && (!is_numeric($value) || $value < 0)) {
                    $error = 1;
                } else {
                    $error = 0;
                }
                break;
            case 'min_length':
                $min_length = $check_hint;
                $error = mb_strlen($value, 'utf-8') < $min_length ? 1 : 0;
                break;
            case 'max_length': # max_length => 15
                $max_length = $check_hint; # expect 15
                $error = mb_strlen($value, 'utf-8') > $max_length ? 1 : 0;
                break;

            case 'boolean': // boolean, allow 0(false) or 1(true)
                $result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === false;
                $error = $result == null ? 1 : 0; # null mean validation error
                $value = $result; # but false mean fail in sanitizeOne..
                break;

            case 'float':
                #    $value = filter_var($sanitized, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
                $error = filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND) === false ? 1 : 0;
                break;

            case 's:float':
                $sanitized = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
                $value = filter_var($sanitized, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
                $error = filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND) === false ? 1 : 0;
                break;

            case 'email':
                $error = filter_var($value, FILTER_VALIDATE_EMAIL) === false ? 1 : 0;
                break;
            case 'e:email':
                if (!empty($value)) {
                    $error = filter_var($value, FILTER_VALIDATE_EMAIL) === false ? 1 : 0;
                }
            case 's:email':
                $value = filter_var($value, FILTER_SANITIZE_EMAIL);
                $error = filter_var($value, FILTER_VALIDATE_EMAIL) === false ? 1 : 0;
                break;

            case 'url':
                $error = filter_var($value, FILTER_VALIDATE_URL) === false ? 1 : 0;
                break;
            #	     	case 's:url':
            #	       		$value = filter_var($value, FILTER_SANITIZE_URL);
            # 	      		$error = filter_var($value, FILTER_VALIDATE_URL) === false? 1 : 0;
            # 	      	break;

            case 'ipv4': # the default, IPv4 only
                $error = filter_var($value, FILTER_VALIDATE_IP) === false ? 1 : 0;
                break;
            case 's:ipv4':
                echo "filter: sanitize IP not available";
                $error = 1;
                break;

            case 's:trim':  # trim leading | trailing space
                $value = trim($value);
                break;
            case 's:strip_tags':  # trim leading | trailing space
                $value = strip_tags($value);
                break;

            case 'equ': # enum值
                $equ = $check_hint;
                $error = !in_array($value, $equ) ? 1 : 0;
                break;

            case 'page': #page參數專用
                if (!is_numeric($value) || empty($value) || $value <= 0) {
                    $value = 1;
                }
                break;
        } # end case
        if ($error > 0) {
            return false; # validate (check) / sanitize (filter) end
        }
    } # end foreach
    return $value;
}

/**
 * Sanitize an array.
 *
 * sanitize($_POST, array('id'=>'int', 'name' => 'str'));
 * $customArray=Array(
 *   [id] => blabla77
 *   [name] => John
 *   [variable1] => somedata
 *   [variable2] => somedata
 * )
 * sanitize($customArray, array('id'=>'int', 'name' => 'str'));
 * @param array $data
 * @param array $whatToKeep
 */
function sanitize(&$data, $whatToKeep) {
    $data = array_intersect_key($data, $whatToKeep);
    foreach ($data as $key => $value) {
        $data[$key] = sanitizeOne($data[$key], $whatToKeep[$key]);
    }
}

/* * ****************** End input data processing ******************* */

// When using UTF-8 as a charset, htmlentities will only convert
// 1-byte and 2-byte characters. Use this function if you also want to convert 3-byte and 4-byte characters:
// converts a UTF8-string into HTML entities
//  - $utf8:        the UTF8-string to convert
//  - $encodeTags:  booloean. TRUE will convert "<" to "&lt;"
//  - return:       returns the converted HTML-string
// echo utf8tohtml($anyUTF8string, TRUE);

function utf8tohtml($utf8, $encodeTags) {
    $result = '';
    for ($i = 0; $i < strlen($utf8); $i++) {
        $char = $utf8[$i];
        $ascii = ord($char);
        if ($ascii < 128) {
            // one-byte character
            $result .= ($encodeTags) ? htmlentities($char) : $char;
        } else if ($ascii < 192) {
            // non-utf8 character or not a start byte
        } else if ($ascii < 224) {
            // two-byte character
            $result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
            $i++;
        } else if ($ascii < 240) {
            // three-byte character
            $ascii1 = ord($utf8[$i + 1]);
            $ascii2 = ord($utf8[$i + 2]);
            $unicode = (15 & $ascii) * 4096 +
                    (63 & $ascii1) * 64 +
                    (63 & $ascii2);
            $result .= "&#$unicode;";
            $i += 2;
        } else if ($ascii < 248) {
            // four-byte character
            $ascii1 = ord($utf8[$i + 1]);
            $ascii2 = ord($utf8[$i + 2]);
            $ascii3 = ord($utf8[$i + 3]);
            $unicode = (15 & $ascii) * 262144 +
                    (63 & $ascii1) * 4096 +
                    (63 & $ascii2) * 64 +
                    (63 & $ascii3);
            $result .= "&#$unicode;";
            $i += 3;
        }
    }
    return $result;
}

/** terry start ************************************************* */
//html编码
function htmlencode($str, $br = 1) {
    if (empty($str))
        return;
    if ($str == "")
        return $str;
    $str = htmlspecialchars($str);
    if ($br == 1) {
        $str = str_replace(chr(13) . chr(10), "<br />", $str);
    }
    return $str;
}

//end htmlencode


/* 截取字符串开始
  @param 	String 	$sourcestr 字符串
  @param 	int		$cutlength 截取長度
  @return String 	截取后的字符串
 */

function wordscut($sourcestr, $cutlength) {
    $returnstr = '';
    $i = 0;
    $n = 0;
    $sourcestr = strip_tags($sourcestr);

    $str_length = strlen($sourcestr); //字符串的字节数

    while (($n < $cutlength) and ($i <= $str_length)) {
        $temp_str = substr($sourcestr, $i, 1);
        $ascnum = Ord($temp_str); //得到字符串中第$i位字符的ascii码
        if ($ascnum >= 224) { //如果ASCII位高与224，
            $returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i = $i + 3; //实际Byte计为3
            $n++; //字串长度计1
        } elseif ($ascnum >= 192) { //如果ASCII位高与192，
            $returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i = $i + 2; //实际Byte计为2
            $n++; //字串长度计1
        } elseif ($ascnum >= 65 && $ascnum <= 90) { //如果是大写字母，
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1; //实际的Byte数仍计1个
            $n++; //但考虑整体美观，大写字母计成一个高位字符
        } else { //其他情况下，包括小写字母和半角标点符号，
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1; //实际的Byte数计1个
            $n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
        }
    }
    //if ($str_length>$cutlength){
    if ($n >= $cutlength) {
        $returnstr = $returnstr . "..."; //超过长度时在尾处加上省略号
    }
    return $returnstr;
}

// end wordscut

/**
 * 補充零函數
 *
 * 可以在不夠位數的數字前面補充0
 *
 * @param int $num 需要填零的數字
 * @param int $zerofill 位數
 * @return int 補充0后的結果
 */
function zerofill($num, $zerofill = 2) {
    while (strlen($num) < $zerofill) {
        $num = "0" . $num;
    }
    return $num;
}

// end zerofill

/**
 * 過濾特殊字符
 * @param 	String $c 	要過濾的字符串
 * @return 	String 		過濾后的字符串
 */
function rp($c) {
    $c = str_replace(" ", "", $c);
    $c = str_replace("'", "", $c);
    $c = str_replace("\"", "", $c);
    $c = str_replace("\/", "", $c);
    $c = str_replace("\\", "", $c);
    $c = str_replace("<", "", $c);
    $c = str_replace(">", "", $c);
    $c = str_replace("#", "", $c);
    $c = str_replace("@", "", $c);
    $c = str_replace("%", "", $c);
    $c = str_replace("&", "", $c);
    $c = str_replace("*", "", $c);
    $c = str_replace("(", "", $c);
    $c = str_replace(")", "", $c);
    $c = str_replace("$", "", $c);
    $c = str_replace("!", "", $c);
    $c = str_replace("^", "", $c);
    $c = str_replace(".", "", $c);
    $c = str_replace(",", "", $c);
    $c = str_replace(";", "", $c);
    return $c;
}

/**
 * 顯示信息跳轉
 * @param String $msg 顯示的信息
 * @param String $url 跳轉的頁面
 */
function showMsgCode($msg, $url = '', $target = '') {

    global $site_global_config;
    $view = $site_global_config['VIEW'];

    include($view . 'showErr.php');
    exit();
}

/**
 * 顯示確認信息選擇跳轉
 * @param String $msg  顯示的信息
 * @param String $url1 確定后跳轉的頁面
 * @param String $url2 取消后跳轉的頁面
 */
function showMsgCodeConfirm($msg, $url1, $url2) {
    if (!$msg || !$url1 || !$url2)
        showMsgCode('Error Return...');

    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n";
    echo "<script type=\"text/javascript\">\r\n";
    echo "<!--\r\n";
    echo "if(confrim(\"" . $msg . "\"){\r\n";
    echo "window.location=\"" . $url1 . "\";\r\n";
    echo "}else{\r\n";
    echo "window.location=\"" . $url2 . "\";\r\n";
    echo "}\r\n";
    echo "-->\r\n";
    echo "</script>";
    exit();
}

/* 轉義字符串 */

function addcheck($str) {
    if (!get_magic_quotes_gpc()) {
        $str = daddslashes($str);
    }
    return $str;
}

function daddslashes($string, $force = 0) {
    if (!isset($GLOBALS['magic_quotes_gpc']) || !$GLOBALS['magic_quotes_gpc'] || $force) {
        if (is_array($string)) {
            foreach ($string as $key => $val) {
                $string[$key] = daddslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
    }
    return $string;
}

function dstripslashes($string) {
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = dstripslashes($val);
        }
    } else {
        $string = stripslashes($string);
    }
    return $string;
}

/**
 * 顯示日期
 * @param int 	$mydate	日期
 * @param String $format 顯示格式
 * @return String
 */
function getmydate($mydate, $format) {
    $week = array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');

    switch ($format) {
        case 'w':
            return $week[date('w', $mydate)];
            break;
    }
}

/**
 * 獲取年齡
 * @param date $birth 日期
 * @return int $age
 */
function getAge($birth) {
    $mybirth = getdate(strtotime($birth));
    $year = $mybirth['year'];
    $month = $mybirth['mon'];
    $day = $mybirth['mday'];

    $ndate = getdate();
    $nyear = $ndate['year'];
    $nmonth = $ndate['mon'];
    $nday = $ndate['mday'];

    $age = $nyear - $year;

    if (($nmonth * 100 + $nday) - ($month * 100 + $day) < 0) {
        $age = $age - 1;
    }
    return $age;
}

function getAgeGroup($age) {
    $ageGroup = 0;
    if ($age <= 19) {
        $ageGroup = 1;
    } elseif ($age >= 20 && $age <= 24) {
        $ageGroup = 2;
    } elseif ($age >= 25 && $age <= 29) {
        $ageGroup = 3;
    } elseif ($age >= 30 && $age <= 34) {
        $ageGroup = 4;
    } elseif ($age >= 35 && $age <= 39) {
        $ageGroup = 5;
    } elseif ($age > 39) {
        $ageGroup = 6;
    }
    return $ageGroup;
}

/**
 * 獲取星座
 * @param date $birth 日期
 * @return int $zod
 */
function getZod($birth) {
    $mybirth = getdate(strtotime($birth));
    $month = $mybirth['mon'];
    $day = $mybirth['mday'];

    if (($month == 3 && $day >= 21) || ($month == 4 && $day <= 20)) {
        return 1;
    } else if (($month == 4 && $day >= 21) || ($month == 5 && $day <= 20)) {
        return 2;
    } else if (($month == 5 && $day >= 21) || ($month == 6 && $day <= 21)) {
        return 3;
    } else if (($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)) {
        return 4;
    } else if (($month == 7 && $day >= 23) || ($month == 8 && $day <= 22)) {
        return 5;
    } else if (($month == 8 && $day >= 23) || ($month == 9 && $day <= 22)) {
        return 6;
    } else if (($month == 9 && $day >= 23) || ($month == 10 && $day <= 22)) {
        return 7;
    } else if (($month == 10 && $day >= 23) || ($month == 11 && $day <= 21)) {
        return 8;
    } else if (($month == 11 && $day >= 22) || ($month == 12 && $day <= 21)) {
        return 9;
    } elseif (($month == 12 && $day >= 22) || ($month == 1 && $day <= 19)) {
        return 10;
    } else if (($month == 1 && $day >= 20) || ($month == 2 && $day <= 18)) {
        return 11;
    } else if (($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)) {
        return 12;
    }
}

/**
 * 生成随机数
 * @param int $length 長度
 * @return string
 */
function randomkey($length) {
    $hash = '';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

/**
 * 字符串解密加密
 *
 * @param string $string  原文或者加密后的密文
 * @param string $operation 默认DECODE 为解密，其他加密
 * @param string $key  密钥
 * @param  int $expiry 加密有效期 0为永不过期  单位秒
 * @return string 加密的密文 或者解密的原文
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

    $ckey_length = 4; // 随机密钥长度 取值 0-32;
    // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
    // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
    // 当此值为 0 时，则不产生随机密钥

    $key = md5($key ? $key : UC_KEY); //UC_KEY 为加密密钥 此为UcHome 中的代码，没有修改
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}

/*
 * @param int $x		原圖width
 * @param int $y		原圖height
 * @param int $o_x	縮圖width
 * @param int $o_y	縮圖height
 * @return 返回圖片尺寸
 */

function changephoto($x, $y, $o_x, $o_y) {
    if ($o_x >= $x && $o_y >= $y) { //原圖比規定尺寸小
        $curx = $x;
        $cury = $y;
    } elseif ($x >= $o_x && $y >= $o_y) {
        if ($x >= $y) {
            $curx = $o_x;
            $cury = intval(($o_x * $y) / $x);
            if ($cury >= $o_y) {
                $curx = intval(($o_y * $o_x) / $cury);
                $cury = $o_y;
            }
        } elseif ($y > $x) {
            $cury = $o_y;
            $curx = intval(($o_y * $x) / $y);
            if ($curx >= $o_x) {
                $cury = intval(($o_x * $o_y) / $curx);
                $curx = $o_x;
            }
        }
    } elseif ($x >= $y) {  //橫圖
        $curx = $o_x;
        $cury = intval(($o_x * $y) / $x);
    } elseif ($y > $x) {  //豎圖
        $cury = $o_y;
        $curx = intval(($o_y * $x) / $y);
    }
    return array('x' => $curx, 'y' => $cury);
}

/**
 * 發送郵件
 * @param string $receiver	收件人地址
 * @param string $sender		發件人地址
 * @param string $subject	電郵主題
 * @param string $content	電郵內容
 * @return bool
 */
function sendMail($receiver, $sender, $subject, $content) {
    if (empty($receiver))
        return false;
    $sender = empty($sender) ? "nmweb@nmg.com.hk" : $sender;
    $subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";    //防止電郵主題亂碼
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";  //設置輸出編碼
    $headers .= "From: " . $sender . "\r\n";        //發件人地址
    $send_status = false;
    if (mail($receiver, $subject, $content, $headers, "-f " . $sender))
        $send_status = true;
    return $send_status;
}

/**
 * 多接收人的郵件發送
 * @param array $receiver_a	收件人地址
 * @param string $sender		發件人地址
 * @param string $subject	電郵主題
 * @param string $content	電郵內容
 */
function sendMailMulti($receiver_a, $sender, $subject, $content) {
    foreach ($receiver_a as $receiver) {
        sendMail($receiver, $sender, $subject, $content);
    }
}

/** terry start */

/** 獲取model對象
 * @param String $modelname  對象名稱
 * @param Array	$param		類參數
 * @return obj
 */
function getModel($modelname, $param = array()) {
    $name = explode('_', $modelname);
    $name = $name[0];
    if ($name != 'Model') {
        $modelname = 'Model_' . $modelname; //兼容沒有Model_開頭的class
    }
    $modelfile = APP_PATH . '/' . str_replace('_', '/', $modelname) . '.php';
    if (file_exists_case($modelfile)) {
        require_cache($modelfile);
        if (empty($param)) {
            return new $modelname;
        } else {
            return new $modelname($param);
        }
    } else {
        return false;
    }
}

/** 獲取lib對象
 * @param String $classname	對象名稱
 * @param Array	$param		類參數
 * @return obj
 */
function getLibClass($classname, $param = array()) {
    $classfile = LIB_PATH . '/Common/' . str_replace('_', '/', $classname) . '.class.php';
    if (file_exists_case($classfile)) {
        require_cache($classfile);
        if (empty($param)) {
            return new $classname;
        } else {
            return new $classname($param);
        }
    } else {
        return false;
    }
}

/** 獲取KVCache對象,回調自定義操作類
 * @param String $classname 	對象名稱
 * @param Array	$param		參數
 * @return obj
 */
function getCacheClass($classname, $param = array()) {
    $classfile = LIB_PATH . '/' . str_replace('_', '/', $classname) . '.class.php';
    if (file_exists_case($classfile)) {
        require_cache($classfile);
        return new $classname('', $param);
    } else {
        return false;
    }
}

/** 獲取KVCache對象
 * @param String $cache_name 	cache對象名稱
 * @param Array	$param			參數
 * @return obj
 */
function getCache($cache_name, $param = array()) {
    return new KVCache($cache_name, $param);
}

/** 優化require_once
 * @param String $filename	require_once的文件名
 * @return String
 */
function require_cache($filename) {
    static $_importFiles = array();
    $filename = realpath($filename);
    if (!isset($_importFiles[$filename])) {
        if (file_exists_case($filename)) {
            require $filename;
            $_importFiles[$filename] = true;
        } else {
            $_importFiles[$filename] = false;
        }
    }
    return $_importFiles[$filename];
}

/** 区分大小写的文件存在判断
 * @param String $filename 文件名
 */
function file_exists_case($filename) {
    if (is_file($filename)) {
        if (basename(realpath($filename)) != basename($filename)) {
            return false;
        }
        return true;
    }
    return false;
}

/** 取得对象实例 支持调用类的静态方法 */
function get_instance_of($type, $mode, $obj = '') {
    static $_instance = array();
    if ($obj) {
        $_instance[$type][$mode] = $obj;
        return $obj;
    } else {
        if (isset($_instance[$type][$mode])) {
            return $_instance[$type][$mode];
        } else {
            return false;
        }
    }
}

/** SOS 輸出提示信息
 * @param String $content 提示內容
 */
function sos($content) {
    $content = "[" . date("Y-m-d H:i:s") . "]" . $content . "\r\n";
    file_put_contents(ROOT_PATH . '/www/sos.txt', $content, FILE_APPEND);
}

/** 獲取訪問ip */
function getip() {
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    } else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else if (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
    } else {
        $cip = "";
    }
    return $cip;
}

/** 獲取microtime */
function get_microtime() {
    list($usec, $sec) = explode(' ', microtime());
    return ((float) $usec + (float) $sec);
}

/** 循環創建文件夾
 * @param String $content 提示內容
 */
function createDirs($dirstr = "") {
    $dirtemp = "";
    if (empty($dirstr))
        return false;
    $dirs = explode("/", $dirstr);
    $dirtemp.=$dirs[0];
    for ($i = 1; $i <= count($dirs) + 1; $i++) {
        if ($dirtemp != "." && $dirtemp != ".." && !empty($dirtemp) && !file_exists($dirtemp)) {
            if (!@mkdir($dirtemp))
                return false;
            chmod($dirtemp, 0777);
        }
        if (!empty($dirs[$i]))
            $dirtemp.="/" . $dirs[$i];
    }
    return true;
}

/** 清空cache
 * @param String $cache_name
 */
function clear_kvcache($cache_name) {

    global $kvcache;

    $cache_logname = get_hash_param($kvcache, 'cache_logname', 'CACHELOGNAME');
    $cache_type = get_hash_param($kvcache, 'cache_type', 'KVMemcache');
    $cache_dbm_path = get_hash_param($kvcache, 'default_dbm_path', CACHE_PATH . '/dbm/');

    if ($cache_type == 'KVMemcache') {   # KVMemcache
        $handle_obj = getCache($cache_logname, array('expire' => 0));

        if ($cache_logname == $cache_name) { # del log
            $handle_obj->del(0);
            echo "del cache " . $cache_name . " success<br>";
            return true;
        }

        $kvcobj = getCache($cache_name);

        $result = $handle_obj->get(0);
        if (isset($result[$cache_name])) {
            echo "del cache " . $cache_name . " success<br>";
            $delkey = $result[$cache_name];
            if (is_array($delkey)) {
                foreach ($delkey as $key) {
                    $kvcobj->del($key);
                    echo "key:" . $key . "\r\n";
                }
            }
            unset($result[$cache_name]);
            $handle_obj->set(0, $result);
        }
    } elseif ($cache_type == 'KVdbm') {  # KVdbm
        $dbmfile = $cache_dbm_path . $cache_name . '.dbm';
        $dbmlck = $cache_dbm_path . $cache_name . '.dbm.lck';
        if (file_exists($dbmfile)) {
            unlink($dbmfile);
            echo "del dbm file:" . $dbmfile . " success<br>";
        }
        if (file_exists($dbmlck)) {
            unlink($dbmlck);
            echo "del dbm lck file:" . $dbmlck . " success<br>";
        }
    }
}

/**
 * 循環顯示內容
 * @param int 	$start  開始數
 * @param int 	$end 	結束數
 * @param int	$cur	當前數
 * @param String $type	循環類型 option,a
 * @return String
 */
function forhtml($start, $end, $cur, $type) {
    $thtml = '';
    switch ($type) {
        case 'option':
            for ($i = $start; $i <= $end; $i++) {
                if ($cur == $i) {
                    $thtml = $thtml . '<option value="' . $i . '" selected>' . $i . '</option>';
                } else {
                    $thtml = $thtml . '<option value="' . $i . '">' . $i . '</option>';
                }
            }
            break;
    }
    return $thtml;
}

/** 過濾特殊字符
 * 	@param	String
 * 	@return String
 */
function FilterPartialUTF8Char($ostr) {
    preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $ostr, $matches);
    $str = join('', $matches[0]);
    if ($str == '') {
        $returnstr = '';
        $i = 0;
        $str_length = strlen($ostr);
        while (($n < 10000) and ($i <= $str_length)) {
            $temp_str = substr($ostr, $i, 1);
            $ascnum = Ord($temp_str);
            if ($ascnum >= 224) {
                $returnstr = $returnstr . substr($ostr, $i, 3);
                $i = $i + 3;
            } elseif ($ascnum >= 192) {
                $returnstr = $returnstr . substr($ostr, $i, 2);
                $i = $i + 2;
            } elseif ($ascnum >= 65 && $ascnum <= 90) {
                $returnstr = $returnstr . substr($ostr, $i, 1);
                $i = $i + 1;
            } elseif ($ascnum >= 128 && $ascnum <= 191) {
                $i = $i + 1;
            } else {
                $returnstr = $returnstr . substr($ostr, $i, 1);
                $i = $i + 1;
            }
        }
        $str = $returnstr;
        preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $str, $matches);
        $str = join('', $matches[0]);
    }
    return $str;
}

/**
 * 顯示圖片的時候根據需要截圖
 *
 * 在顯示圖片的時候，根據界面給定的大小，自動截取縮略圖，若縮略圖已經生成，則直接返回縮略圖
 *
 * @param string $pic 圖片絕對路徑
 * @param int $w 指定的寬度
 * @param int $hh 指定的高度
 * @param  int $wpos 水印
 * @param  int $resetwidth 指定寬度重設高度
 * @return string 返回縮略圖的路徑
 */
function showphoto($pic, $w = 0, $hh = 0, $wpos = 0, $resetwidth = 0, $square = 0) {

    $h = $hh;
    $nopic = 0;

    if (!is_file($pic)) {
        $pic = ROOT_PATH . "/www/upload/default_photo_new.jpg";
        $nopic = 1;
    }

    $path = dirname($pic) . "/";

    if (strtolower(substr(strrchr($pic, "."), 1)) <> 'jpg') {
        $topic = dirname($pic) . '/' . basename($pic, strtolower(substr(strrchr($pic, "."), 1))) . '.jpg';

        if (!file_exists($topic)) {
            //exec("convert \"".$pic."\" '-quality' 90  '-flatten' \"".$topic."\"");
            exec("convert \"" . $pic . "\" '-quality' 100  '-flatten'  \"" . $topic . "\"");
        }
        $pic = $topic;
    }


    if (!file_exists($path . ($tmp = basename($pic) . "-{$w}x{$h}-{$wpos}.jpg"))) {


        // convert -define jpeg:size=200x200 hatching_orig.jpg -thumbnail '100x100>'
        //-background skyblue -gravity center -extent 100x100 pad_extent.gif
        //composite -define jpeg:size=200x200 -resize '100x100>' -gravity
        //center hatching_orig.jpg background.gif composite.gif

        if ($nopic) {
            $str = "convert " . $pic . " -thumbnail '" . $w . "x" . $h . ">' -quality 100  -background 'rgb(234,234,234)' -gravity center -extent  " . $w . "x" . $h . " " . $path . $tmp;
        } else {
            $str = "convert " . $pic . " -thumbnail '" . $w . "x" . $h . ">' -quality 100  -background white -gravity center -extent  " . $w . "x" . $h . " " . $path . $tmp;
        }
        //SOS($str);
        $result = exec($str);
    }

    return str_replace(ROOT_PATH . "/www/", '', '/' . $path . $tmp);
}

/**
 * 顯示圖片的時候根據需要截圖
 *
 * 在顯示圖片的時候，根據界面給定的大小，自動截取縮略圖，若縮略圖已經生成，則直接返回縮略圖
 *
 * @param string $pic 圖片絕對路徑
 * @param int $w 指定的寬度
 * @param int $hh 指定的高度
 * @param  int $wpos 水印
 * @param  int $resetwidth 指定寬度重設高度
 * @return string 返回縮略圖的路徑
 */
function showphotoCenter($pic, $w = 0, $hh = 0, $wpos = 0, $resetwidth = 0, $square = 0) {

    $h = $hh;


    $pic = is_file($pic) ? $pic : ROOT_PATH . "/www/upload/default_photo_new.jpg";
    $path = dirname($pic) . "/";

    if (strtolower(substr(strrchr($pic, "."), 1)) <> 'jpg') {
        $topic = dirname($pic) . '/' . basename($pic, strtolower(substr(strrchr($pic, "."), 1))) . '.jpg';

        if (!file_exists($topic)) {
            //exec("convert \"".$pic."\" '-quality' 90  '-flatten' \"".$topic."\"");
            exec("convert \"" . $pic . "\" '-quality' 100  '-flatten'  \"" . $topic . "\"");
        }
        $pic = $topic;
    }


    $temp_img = @imagecreatefromjpeg($pic);
    if ($temp_img) {
        $o_width = @imagesx($temp_img);    //取得原圖寬
        $o_height = @imagesy($temp_img);
        /*
          if($w==500 && $o_width<500){
          $w = $o_width;
          $h = $o_height;
          }
         */
        if ($resetwidth && $w) {
            $h = intval($o_height * $w / $o_width);
        }

        if ($resetwidth) {
            if ($h > $hh) {
                $h = $hh;
                $w = intval($o_width * $h / $o_height);
            }
        }
    }

    if (!file_exists($path . ($tmp = basename($pic) . "-s-{$w}x{$h}-{$wpos}.jpg"))) {
        cutphoto($pic, $path . $tmp, $w, $h, 100);
        /*
          //if ($wpos!=0) imageWaterMark($path.$tmp,$wpos);
          if(strlen($wpos)==1){				//沒有選水印圖片的用默認圖
          $wpos = $wpos ."-0";
          }

          $twpos = explode("-",$wpos);
          if($twpos[0]!=0){
          imageWaterMark($path.$tmp,$wpos);
          }
         */
    }

    return str_replace(ROOT_PATH . "/www/", '', '/' . $path . $tmp);
}

/**
 * 按比例截取圖片
 *
 * 按設定的高和寬，自動截取部分適應比例的大小圖片
 *
 * @param string $o_photo 原图路径
 * @param string $d_photo 处理后图片路径
 * @param int $width 定义宽
 * @param int $height 定义高
 * @return string 圖片路徑
 */
function cutphoto($o_photo, $d_photo, $width, $height, $q = 90) {
    if (strtolower(substr(strrchr($o_photo, "."), 1)) <> 'jpg') {
        $topic = dirname($o_photo) . '/' . basename($o_photo, strtolower(substr(strrchr($o_photo, "."), 1))) . '.jpg';
        if (!file_exists($topic)) {
            exec("convert \"" . $o_photo . "\"  +profile \"*\"  '-quality' $q  '-flatten'  \"" . $topic . "\"");
        }
        $o_photo = $topic;
    }
    $temp_img = @imagecreatefromjpeg($o_photo);
    $o_width = @imagesx($temp_img);    //取得原圖寬
    $o_height = @imagesy($temp_img);    //取得原圖高
    $width = $width ? $width : $o_width;
    $height = $height ? $height : $o_height;

    if (file_exists($o_photo)) {
        if ($temp_img) {
            if ($o_width == $width && $o_height == $height) {
                copy($o_photo, $d_photo);
            } else {
                if (($r_o = $o_width / $o_height) == ($r_d = $width / $height)) {
                    $src_x = $src_y = 0;
                    $src_w = $o_width;
                    $src_h = $o_height;
                } else if ($r_o > $r_d) {
                    //原圖比新圖闊
                    $src_y = 0;
                    $src_h = $o_height;
                    $src_w = $r_d * $src_h;
                    $src_x = ($o_width - $src_w) / 2;
                } else {
                    //原圖比新圖高
                    $src_x = 0;
                    $src_w = $o_width;
                    $src_h = $src_w / $r_d;
                    $src_y = ($o_height - $src_h) / 2;
                }
                $new_img = imagecreatetruecolor($width, $height);
                imagecopyresampled($new_img, $temp_img, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
                imagejpeg($new_img, $d_photo, $q);
                imagedestroy($new_img);
            }
        }
    }
}

/**
 * 後臺分頁函數
 *
 * 處理并顯示分頁
 *
 * @param int $num 總條目數量
 * @param int $perpage 每頁顯示數目
 * @param int $curpage 當前頁數
 * @param string $mpurl 分頁連接，請注意要傳遞的參數不要遺漏
 * @param int $maxpages 最多顯示頁數
 * @return string 分頁
 */
function showPage($num, $perpage = 3, $curpage = 1, $mpurl, $maxpages = 0, $aname = '') {

    $is_html = 0;
    $file_type = "";
    $file_type = strtolower(substr(strrchr($mpurl, "."), 1));
    $file_type_array = explode("?", $file_type);
    if ($file_type_array)
        $file_type = $file_type_array[0];


    if ($file_type == 'html') {
        $is_html = 1;
        $mpurl = dirname($mpurl) . '/' . basename($mpurl, ".html");
        //$mpurl .= '-';
    } elseif ($file_type == 'php') {
        $is_html = 2;
        $mpurl .= strpos($mpurl, '?') ? '&' : '?';
    } else {
        $is_html = 3;
        //$mpurl .= '/';
    }


    if (!intval($perpage))
        return;
    $multipage = '';
    if ($num > $perpage) {
        $page = 10;
        $offset = 5;

        $realpages = ceil($num / $perpage);
        $pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

        $from = $curpage - $offset;
        $to = $curpage + $page - $offset - 1;
        if ($page > $pages) {
            $from = 1;
            $to = $pages;
        } else {
            if ($from < 1) {
                $to = $curpage + 1 - $from;
                $from = 1;
                if (($to - $from) < $page && ($to - $from) < $pages) {
                    $to = $page;
                }
            } elseif ($to > $pages) {
                $from = $curpage - $pages + $to;
                $to = $pages;
                if (($to - $from) < $page && ($to - $from) < $pages) {
                    $from = $pages - $page + 1;
                }
            }
        }

        if ($is_html == 1) {
            $multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="' . $mpurl . '-1.html' . $aname . '" >earliest</a>' : '') .
                    ($curpage > 1 ? '<a href="' . $mpurl . '-' . ($curpage - 1) . '.html' . $aname . '" class="tri prev">上一頁</a>' : '');
            for ($i = $from; $i <= $to; $i++) {
                $multipage .= $i == $curpage ? '<strong>' . $i . '</strong>' :
                        '<a href="' . $mpurl . '-' . $i . '.html' . $aname . '">' . $i . '</a>';
            }

            $multipage .= ($curpage < $pages ? '<a href="' . $mpurl . '-' . ($curpage + 1) . '.html' . $aname . '" class="tri next">下一頁</a>' : '') .
                    ($curpage + $page - $offset <= $pages ? '<a href="' . $mpurl . '-' . $pages . '.html' . $aname . '" >oldest</a>' : '') .
                    ($curpage == $maxpages ? '<a href="' . $mpurl . '-' . $maxpages . '.html' . $aname . '" >oldest</a>' : '');
        } elseif ($is_html == 2) {
            $multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="' . $mpurl . 'page=1' . $aname . '" >earliest</a>' : '') .
                    ($curpage > 1 ? '<a href="' . $mpurl . 'page=' . ($curpage - 1) . $aname . '" class="tri prev">上一頁</a>' : '');
            for ($i = $from; $i <= $to; $i++) {
                $multipage .= $i == $curpage ? '<strong>' . $i . '</strong>' :
                        '<a href="' . $mpurl . 'page=' . $i . $aname . '">' . $i . '</a>';
            }

            $multipage .= ($curpage < $pages ? '<a href="' . $mpurl . 'page=' . ($curpage + 1) . $aname . '" class="tri next">下一頁</a>' : '') .
                    ($curpage + $page - $offset <= $pages ? '<a href="' . $mpurl . 'page=' . $pages . $aname . '" >oldest</a>' : '') .
                    ($curpage == $maxpages ? '<a href="' . $mpurl . 'pages=' . $maxpages . $aname . '" >oldest</a>' : '');
        } else {
            $multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="' . $mpurl . '/1' . $aname . '" >earliest</a>' : '') .
                    ($curpage > 1 ? '<a href="' . $mpurl . '/' . ($curpage - 1) . '' . $aname . '" class="tri prev">上一頁</a>' : '');
            for ($i = $from; $i <= $to; $i++) {
                $multipage .= $i == $curpage ? '<strong>' . $i . '</strong>' :
                        '<a href="' . $mpurl . '/' . $i . '' . $aname . '">' . $i . '</a>';
            }

            $multipage .= ($curpage < $pages ? '<a href="' . $mpurl . '/' . ($curpage + 1) . '' . $aname . '" class="tri next">下一頁</a>' : '') .
                    ($curpage + $page - $offset <= $pages ? '<a href="' . $mpurl . '/' . $pages . '' . $aname . '" >oldest</a>' : '') .
                    ($curpage == $maxpages ? '<a href="' . $mpurl . '/' . $maxpages . '' . $aname . '" >oldest</a>' : '');
        }


        //($pages > $page ? '第<input type="text" name="custompage" size="2" style="border: 1px solid " onKeyDown="javascript: if(event.keyCode == 13) window.location=\''.$mpurl.'page=\'+this.value;">頁' : '');

        $multipage = $multipage ? '' .
                '<div class="page">' . $multipage . '</div>' .
                '' : '';
    }
    return $multipage;
}

/* $data = array(
  'type' => 'p',	//圖表類型為2D餅圖
  'width' => '130',	//圖片寬度
  'height' => '130',	//圖片高度
  'datas' => array(1,2,3,4,5),	//圖片數據
  'colorType' => 1,	//圖片分欄顏色
  'bgcolor' => 'FFFFFF'	//圖片背景顏色
  ) */

function getImgUrl($data = array()) {

    $colors = array(//圖片分欄顏色
        1 => array('B31B54', 'C91B60', 'E84F6D', 'E4757E', 'ECA7B9'),
        2 => array('0342CF', '4075DF', '3294EB', '6BB2F2', '9CCAEC')
    );
    $_type = !empty($data['type']) ? $data['type'] : 'p'; //圖表類型為2D餅圖
    $_width = !empty($data['width']) ? $data['width'] : '130'; //圖片寬度
    $_height = !empty($data['height']) ? $data['height'] : '130'; //圖片高度


    $data_null = 0;
    foreach ($data['datas'] as $k => $v) {
        $data_null += $v;
    }
    if ($data_null <= 0) {
        $data['datas'][count($data['datas']) - 1] = 1;
    }

    $_data = !empty($data['datas']) ? implode(',', $data['datas']) : implode(',', array(1, 2, 3, 4, 5)); //圖片數據
    $_color = !empty($data['colorType']) ? implode('|', $colors[$data['colorType']]) : implode('|', $colors[1]); //圖片分欄顏色
    $_bgcolor = !empty($data['bgcolor']) ? $data['bgcolor'] : 'FFFFFF'; //圖片背景顏色

    $ImgUrl = "http://chart.apis.google.com/chart?cht=" . $_type . "&chs=" . $_width . "x" . $_height . "&chd=t:" . $_data . "&chf=bg,s," . $_bgcolor . "&chco=" . $_color;
    return $ImgUrl;
}

//验证的邮件地址
function is_email($email) {
    $chars = "/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/i";
    if (strpos($email, '@') !== false && strpos($email, '.') !== false) {
        if (preg_match($chars, $email)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

//檢查註冊生日
function check_birthday($birthday) {
    if (!isset($birthday) || $birthday == "") {
        return false;
    }
    list($yy, $mm, $dd) = explode("-", $birthday);
    if ($dd != "" && $mm != "" && $yy != "") {
        return checkdate($mm, $dd, $yy);
    }
    return false;
}

//youtube url 轉換
//$p['w']寬  $p['h']高
function youtube($url, $p = array()) {
    $v = '';
    if (!empty($url)) {
        $url = explode('?', $url);
        parse_str($url[1], $t);
        $v = $t['v'];
    }
    $u = 'http://s.ytimg.com/yt/swfbin/watch_as3-vfl9enKfv.swf';
    if ($v) {
        $u = 'http://www.youtube.com/v/' . $v . '&hl=zh_CN&fs=1';
    }
    $wh = 'width="' . $p['w'] . '" height="' . $p['h'] . '"';
    $r = '<object ' . $wh . ' ><param name="movie" value="' . $u . '" /><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><embed  wmode="transparent" src="' . $u . '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true"  ' . $wh . '  ></embed></object>';
    return $r;
}

/**
 * 圖片或文件上傳函數
 *
 * @param string $uploaddir 要保存文件的絕對路徑
 * @param string $f_input 表單的名字 表單需要用數組 例如 photo[0]
 * @param string $f_type 上傳的文件類型
 * @param int $file_size_max 上傳的文件大小
 * @return array 返回已上傳的圖片名稱數組
 */
function uploadfiles($uploaddir, $f_input = 'temp', $f_type = "jpg,jpeg,gif,png", $file_size_max = 10485760) {

    $sess = new Session();
    $member = $sess->get('memberData');
    $overwrite = 0;

    if (function_exists('date_default_timezone_set')) {
        date_default_timezone_set('PRC');
    }//設置時區
    
   //echo '<pre>' . var_export($f_input, 1) . '</pre>';
   //exit();
   
    
    
    $return = array();
    if ($_FILES[$f_input]) {
        foreach ($_FILES[$f_input]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK) {
                $f_name = $_FILES[$f_input]['name'][$key]; //獲取上傳源文件名
                $uploadfile = $uploaddir . strtolower(basename($f_name));

                $tmp_type = strtolower(substr(strrchr($f_name, "."), 1)); //獲取文件擴展名
                if (!strstr($f_type, $tmp_type)) {
                    $return[$key]['code'] = 0;
                    $return[$key]['msg'] = "上傳失敗！不能上傳" . $tmp_type . "格式文件, " . $f_name . " 文件上傳失敗!";
                } elseif ($_FILES[$f_input]['size'][$key] > $file_size_max) {
                    $return[$key]['code'] = 0;
                    $return[$key]['msg'] = "你上傳的 " . $f_name . " 文件，容量大於10MB，請重新上傳。";
                } elseif (file_exists($uploadfile) && !$overwrite) {
                    $return[$key]['code'] = 0;
                    $return[$key]['msg'] = "對不起,文件 " . $f_name . "已經存在,上傳失敗!";
                } else {

                    $attr = array();
                    $attr['addtime'] = date('Y-m-d H:i:s');
                    $attr['uid'] = ($member) ? $member['id'] : 0;
                    $id = db_add('photos', $attr);

                    $pic_path = $uploaddir . "/" . date('Y') . "/" . date('m') . "/" . date('d');
                    createDirs($pic_path);
                    $uploadfile_path = $pic_path . "/" . date("YmdHis") . "_" . microtime() * 1000000 . "_" . rand(10, 99) . $key . "_" . $id . "_" . $attr['uid'] . "." . $tmp_type;
                    //$filen[$key] = $uploadfile_path;
                    if (move_uploaded_file($_FILES[$f_input]['tmp_name'][$key], $uploadfile_path)) {
                        @chmod($uploadfile_path, 0777);
                        $return[$key]['code'] = 1;
                        $return[$key]['filename'] = $f_name;
                        $return[$key]['path'] = $uploadfile_path;
                        $return[$key]['size'] = $_FILES[$f_input]['size'][$key];

                        global $site_global_config;
                        $root = $site_global_config['WWW'];
                        db_update('photos', array('photo_url' => str_replace($root, "", $uploadfile_path)), 'id=' . $id);
                    } else {
                        $return[$key]['code'] = 0;
                        $return[$key]['msg'] = "對不起,文件 " . $f_name . "上傳失敗!";
                        db_update('photos', array('status' => 0), 'id=' . $id);
                    }
                }
            }
        }
    }
    return $return;
}

/**
 * 往後時間差
 * @param string $datetime as '2012-12-12 12:00:00'
 *
 */
function time_to_str($datetime) {
    $diff = time() - strtotime($datetime);
    $diffday = (int) ($diff / 86400);
    $diffhour = (int) (($diff - $diffday * 86400) / 3600);
    $diffminute = (int) (($diff - $diffday * 86400 - $diffhour * 3600) / 60);
    $diffsecond = $diff - $diffday * 86400 - $diffhour * 3600 - $diffminute * 60;

    $_difTime = '';
    if ($diffday > 0)
        $_difTime = $diffday . '天前';
    elseif ($diffhour > 0)
        $_difTime = $diffhour . '小時前';
    elseif ($diffminute > 0)
        $_difTime = $diffminute . '分鐘前';
    elseif ($diffsecond > 0)
        $_difTime = '剛剛';
    return $_difTime;
}

/**
 * 往前時間差
 * @param string $datetime as '2012-12-12 12:00:00'
 *
 */
function str_diff_time($datetime) {
    $diff = strtotime($datetime) - time();
    $diffday = (int) ($diff / 86400);
    $diffhour = (int) (($diff - $diffday * 86400) / 3600);
    $diffminute = (int) (($diff - $diffday * 86400 - $diffhour * 3600) / 60);
    $diffsecond = $diff - $diffday * 86400 - $diffhour * 3600 - $diffminute * 60;

    $_difTime = '';
    if ($diffday > 0)
        $_difTime = $diffday . ' 1';
    elseif ($diffhour > 0)
        $_difTime = $diffhour . ' 2';
    elseif ($diffminute > 0)
        $_difTime = $diffminute . ' 3';
    elseif ($diffsecond > 0)
        $_difTime = $diffsecond . ' 4';
    return $_difTime;
}

/**
 * 顯示右邊欄模塊
 * @param string $b  block.php對應block的action名
 * @param string $iframe  是否調用iframe
 */
function show_block($b, $iframe = 0, $div_id = '', $div_class = '', $url_param = '') {
    if ($div_class == 'sidebar_facebook') {
        global $site_global_config;
        $global_url = $site_global_config['URL'];
        //echo file_get_contents($global_url."block.php?action=".$b."");

        echo '<div ' . $_id . ' ' . $_classes . '><iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fimorehk&amp;width=300&amp;height=427&amp;show_faces=false&amp;colorscheme=light&amp;stream=true&amp;border_color&amp;header=true&amp;appId=354781247936831" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:300px; height:427px;" allowTransparency="true"></iframe></div>';
    } elseif ($div_class == 'fb') {
        echo '<iframe style="float:right;padding:0px;margin:0px;" frameborder="0" width="67px" height="28px" marginwidth="0px" marginheight="0px" scrolling="no" src="/block.php?action=fb' . $url_param . '"></iframe>';
    } else {
        $div_id = trim($div_id);
        $div_class = trim($div_class);
        $_id = empty($div_id) ? '' : "id='" . $div_id . "'";
        $_classes = empty($div_class) ? '' : "class='" . $div_class . "'";
        if (empty($div_class)) {
            $_class = '';
        } else {
            $temp = explode(' ', $div_class);
            $_class = $temp[0];
        }

        if (empty($iframe)) {
            $_ret = "<div " . $_id . " " . $_classes . " ></div>";
            $_ret .= "<script>$.post('/block.php?action=" . $b . $url_param . "',null,function(result){";
            if (!empty($div_id)) {
                $_ret .= "$('#" . $div_id . "').html(result)});</script>";
            } else {
                $_ret .= "$('." . $_class . "').html(result)});</script>";
            }
            echo $_ret;
        } else {
            if ($iframe == 2) {
                //$str="onload='this.height=this.contentWindow.document.documentElement.scrollHeight;";
                $str = "height=92";
            } else {
                $str = "height=250";
            }
            echo "<div " . $_id . " " . $_classes . "><iframe src='/block.php?action=" . $b . "' scrolling='no' frameborder='0' " . $str . "></iframe></div>";
        }
    }
}

/**
 * 判斷數組值是否為正整數
 *
 */
function is_num($arr) {
    $r = "^[0-9]+$";
    foreach ($arr as $v) {
        if (!eregi($r, trim($v))) {
            return 0;
        }
    }
    return 1;
}

function imore_avatar($avatar) {
    if (strstr($avatar, "http://"))
        return $avatar;

    if (!($avatar))
        return DOMAIN . "upload/default_photo.jpg-56x56-0.jpg";
    $url = explode("/avatar/photo/", $avatar);
    $avatarUrl = IMOREDOMAIN . $url[0] . "/avatar/80x80_photo/" . $url[1];

    return $avatarUrl;
}

/**
 * url轉換
 *
 * @param string $php 例如 product
 * @param string $action 例如 invite_list
 * @param string $param_str 例如 mtype=1&pid=1
 * @param int $mode 1:返回轉化后url，0:返回不轉化url
 * @return string
 */
function optimize_url($php = '', $action = '', $param_str = '', $mode = 1) {
    $url = '';
    $php = trim($php);
    $action = trim($action);
    $mode = intval($mode);
    $param = $param_temp = $param_temp1 = array();

    if (!empty($param_str)) {
        $param_temp = explode('&', $param_str);
        if (!empty($param_temp)) {
            foreach ($param_temp as $v) {
                $param_temp1 = explode('=', $v);
                if (!empty($param_temp1)) {
                    $param[$param_temp1[0]] = $param_temp1[1];
                }
            }
        }
    }

    //list、php、action(array)下須有default值
    $list = array(
        'product' => array(
            'invite_list' => array(
                'mtype' => array(
                    1 => '/trialist/invite-[order].html',
                    5 => '/expert/invite-[order].html'
                ),
                'default' => '/trialist/invite.html'
            ),
            'submitReport_list' => array(
                'mtype' => array(
                    1 => '/trialist/submit.html',
                    5 => '/expert/submit.html'
                ),
                'default' => '/trialist/submit.html'
            ),
            'submit_application' => array(
                'mtype' => array(
                    1 => '/trialist/application-[pid].html',
                    5 => '/expert/application-[pid].html'
                ),
                'default' => '/'
            ),
            'invite_inpage' => array(
                'mtype' => array(
                    1 => '/trialist/invite-inpage-[pid].html',
                    5 => '/expert/invite-inpage-[pid].html'
                ),
                'default' => '/'
            ),
            'report_inpage' => array(
                'mtype' => array(
                    1 => '/trialist/report-inpage-[pid].html',
                    5 => '/expert/report-inpage-[pid].html'
                ),
                'default' => '/'
            ),
            'detail' => array(
                'mtype' => array(
                    1 => '/trialist/detail-[pid]-[t].html',
                    5 => '/expert/detail-[pid]-[t].html',
                ),
                'default' => '/'
            ),
            'reportDetail' => array(
                'mtype' => array(
                    1 => '/trialist/report-detail-[pid]-[rid].html',
                    5 => '/expert/report-detail-[pid]-[rid].html',
                ),
                'default' => '/'
            ),
            'readReport_list' => array(
                'mtype' => array(
                    1 => '/trialist/read-report-[ptype]-[order].html',
                    5 => '/expert/read-report-[ptype]-[order].html',
                ),
                'default' => '/trialist/read-report.html'
            ),
            'report_show' => '/report-show-[pid]-[aid]-[or]-[issubmit].html',
            'report_add' => '/report-add-[pid].html',
            'report_edit' => '/report-edit-[pid]-[rid].html',
            'default' => '/trialist/invite.html'
        ),
        'events' => array(
            'invite_list' => '/event/invite-[type]-[s].html',
            'submit_application' => '/event/application-[eid].html',
            'invite_inpage' => '/event/invite-inpage-[eid].html',
            'invite_result' => '/event/result-[eid].html',
            'detail' => '/event/detail-[eid].html',
            'show' => '/event/show-[eid]-[aid]-[or].html',
            'default' => '/event/invite.html'
        ),
        'help' => array(
            'show' => '/guide-[page]-[tag].html',
            'policy' => '/policy.html',
            'about' => '/about-us.html',
            'contactus' => '/contact-us.html',
            'tutorials' => '/tutorials-[step]-[page].html',
            'default' => '/guide.html'
        ),
        'index' => array(
            'list' => '/',
            'default' => '/'
        ),
        'person' => array(
            'report' => '/user/[username]',
            'attention' => '/user/[username]-follow-[t]-[ps].html',
            'recommen' => '/user/[username]-recommend.html',
            'default' => '/user/[username]'
        ),
        'search' => array(
            'product' => '/search-product/[find]',
            'event' => '/search-event/[find]',
            'member' => '/search-member/[find]',
            'default' => '/search-product/[find]',
        ),
        'member' => array(
            'default' => '/'
        ),
        'member_center' => array(
            'default' => '/'
        ),
        'default' => '/'
    );

    if ($mode == 1) {
        $url = $list['default'];
        $_temp = empty($list[$php]) ? $list['default'] : (empty($list[$php][$action]) ? $list[$php]['default'] : $list[$php][$action]);

        if (empty($param)) {
            $url = !empty($_temp) ? (is_array($_temp) ? $_temp['default'] : $_temp) : $url;
        } else {
            $url = foreach_param($param, $_temp);
            foreach ($param as $k => $v) {
                $url = str_replace('[' . $k . ']', $v, $url);
            }
        }
        $url = preg_replace('/\[[a-zA-Z0-9_]+\]/', '0', $url);
    } else {
        if (!empty($list[$php]) && !empty($list[$php][$action])) {
            $url = $php . '.php?action=' . $action;
            if (!empty($param)) {
                foreach ($param as $key => $value) {
                    $url .= '&' . $key . '=' . $value;
                }
            }
        } else {
            $url = 'index.php';
        }
    }
    return $url;
}

//匹配optimize_url 的數組參數
function foreach_param($param, $_temp) {
    if (!empty($param)) {
        foreach ($param as $key => $value) {
            if (is_array($_temp)) {
                if (!empty($_temp[$key]) && !empty($_temp[$key][$value])) {
                    $_temp = $_temp[$key][$value];
                    $_temp = foreach_param($param, $_temp);
                    break;
                }
            } else {
                return $_temp;
            }
        }
    }
    return $_temp;
}

function br2nl($text) {
    return preg_replace('/<br\\s*?\/??>/i', '', $text);
}

/**
 * 截圖圖片
 *
 * @param int $x 截取坐標
 * @param int $y 截取坐標
 * @param int $w 截取寬度
 * @param int $h 截取高度
 * @param int $width 生成寬度
 * @param int $height 生成高度
 * @param string $photo 圖片路徑
 * @return string 圖片絕對路徑
 */
function cropPhoto($x, $y, $w, $h, $width, $height, $photo) {
    $img_r = imagecreatefromjpeg($photo);
    $dst_r = ImageCreateTrueColor($width, $height);
    imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $width, $height, $w, $h);
    $filename = dirname($photo) . '/' . basename($photo, strtolower(substr(strrchr($photo, "."), 1))) . '-crop.jpg';

    $result = imagejpeg($dst_r, $filename, 100);
    if ($result) {
        return $filename;
    }
}

/**
 * @param array $data 傳遞數據
 * @param string $callbackfunc iframe返回的函數名
 * @param array $ret_arr 返回狀態數據，recode為返回狀態，msg為返回信息
 */
function iframe_callback($data = array(), $callbackfunc = "callback", $ret_arr = array("retcode" => 0, "msg" => "")) {
    $ret_arr['data'] = $data;
    header('Content-type: text/html; charset=utf8');
    echo "<script>parent." . $callbackfunc . "(" . json_encode($ret_arr) . ");</script>";
    exit;
}

?>